package com.pureut.storage.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.storage.domain.*;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.ProductionPickingExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.util.UnitUtil;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.utils.MaxNumberUtils;
import com.pureut.storage.vo.*;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.domain.R;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.dict.utils.DictUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.*;
import com.sale.system.api.domain.SysAuxiliary;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.SysUser;
import com.sale.system.api.domain.dto.SysDocumentResultDto;
import com.sale.system.api.model.MaterialUnitDto;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 领料出库实现层
 *
 * @author: CM
 * @date: 2022/12/23  13:46
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class StockOutInfoServiceImpl extends ServiceImpl<StockOutInfoMapper, StockOutInfo> implements StockOutInfoService {


    @NonNull
    StockOutInfoMapper stockOutInfoMapper;

    @NonNull
    WarehouseMapper warehouseMapper;

    //库存
    @NonNull
    WmsStockInfoMapper wmsStockInfoMapper;

    @NonNull
    private StockOutInfoDetailMapper stockOutInfoDetailMapper;

    @NonNull
    private StockInfoDetailService stockInfoDetailService;

    /**
     * 条码打印
     */
    @NonNull
    private BarCodePrintingService barCodePrintingService;

    /**
     * 远程调用单据配置
     */
    @DubboReference
    RemoteDocumentService remoteDocumentService;

    //员工信息
    @NonNull
    private RemoteUserService remoteUserService;

    //仓库建模
    @NonNull
    private WmsStockInfoService wmsStockInfoService;

    //公共物料
    @NonNull
    private PublicMaterialMapper publicMaterialMapper;

    //拣货提示
    @NonNull
    private PickingSchemeService pickingSchemeService;

    @NonNull
    private PickingSaleService pickingSaleService;

    @NonNull
    private PickingOutsourceService pickingOutsourceService;

    @NonNull
    private PickingRestService pickingRestService;

    @NonNull
    private PickingReturnsService pickingReturnsService;

    @NonNull
    private AllotManagementService allotManagementService;

    @NonNull
    private PickingCompleteService pickingCompleteService;

    @NonNull
    private PickingPurchaseService pickingPurchaseService;

    /**
     * 单位Mapper
     */
    @DubboReference
    RemoteUnitService remoteUnitService;

    /**
     * 远程调用菜单管理
     */
    @DubboReference
    RemoteMenuService remoteMenuService;

    /**
     * 编码生成配置
     */
    @DubboReference
    private final RemoteCodeService remoteCodeService;

    @NonNull
    private OutboundLogService outboundLogService;

    @NonNull
    private OutboundLogMapper outboundLogMapper;

    @NonNull
    private BarCodePrintingMapper barCodePrintingMapper;

    @Resource
    UnitUtil unitUtil;


    /**
     * 新增生产领料单
     *
     * @param productionPickingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProductionPicking(ProductionPickingVo productionPickingVo) throws Exception {
        List<ProductionPickingRelationVo> list = productionPickingVo.getList();

        List<StockOutInfo> productionPickinglist = new ArrayList<>();
        if (list.size() > 0) {

            for (ProductionPickingRelationVo productionPickingRelationVo : list) {
                StockOutInfo stockOutInfo = new StockOutInfo();
                BeanUtils.copyProperties(productionPickingVo, stockOutInfo);
                BeanUtils.copyProperties(productionPickingRelationVo, stockOutInfo);


                String sn = remoteCodeService.authorityCoding("warehouse:outbound:producfield:list");
                if (sn == null) {
                    throw new GlobalException("该单据未进行配置,无法生成单据编码");
                }

                stockOutInfo.setCreateUser(LoginHelper.getUsername())
                    .setCreateTime(new Date())
                    .setDocumentType(DocumentTypeEnum.PRODUCTION_PICKING.getCode())
                    .setWodDocNum(sn)
                    .setDeptId(LoginHelper.getDeptId())
                    .setWodStatus(1)
                    .setSalesOrderNum(productionPickingVo.getSalesOrderNum())
//                    .setMaterialUnit(productionPickingRelationVo.getMaterialUnit())
                    .setDateDelivery(productionPickingVo.getDateDelivery())
                    .setGenerationMode(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
                productionPickinglist.add(stockOutInfo);
/*
                String moNumber = productionPickingRelationVo.getMoNumber();

                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, stockOutInfo.getMaterialCode()));
                if((moNumber.contains("SC"))) {
                boolean b = feignProductionService.getInfo(stockOutInfo.getMoNumber());
                    if (!b) {
                        FeedRecord feedRecord = new FeedRecord();
                        feedRecord.setFeedOrderNumber(stockOutInfo.getMoNumber());
                        feedRecord.setLineCode(productionPickingVo.getProductionLine());
                        feedRecord.setMaterialCode(stockOutInfo.getMaterialCode());
                        feedRecord.setMaterialName(publicGoods.getMaterialName());
                        feedRecord.setMaterialSpec(publicGoods.getMaterialSpec());
                        feedRecord.setDeliveryWeight(stockOutInfo.getPlannedWeight());
                        feedRecord.setInvestedWeight(0);
                        feedRecord.setFeedType("1");
                        feedRecord.setCreateBy(LoginHelper.getUsername());
                        AjaxResult add = feignProductionService.add(feedRecord);
                    }
                }*/
            }

            return saveBatch(productionPickinglist);
        } else {
            throw new GlobalException("请至少添加一条物料明细");
        }

    }

    /**
     * 查询生产领料单列表
     *
     * @param productionPickingVo
     * @return
     */
    @Override
    public TableDataInfo<StockOutInfoDto> getList(ProductionPickingVo productionPickingVo, PageQuery pageQuery) throws Exception {
        Page<StockOutInfoDto> stockOutInfos = stockOutInfoMapper.getproductionPickingList(pageQuery.build(), productionPickingVo);

        //获取单据状态字典数据
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "stock_out_info_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取单据状态字典数据
        List<SysDictData> typeArray = CacheUtils.get(CacheNames.SYS_DICT, "stock_out_info_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();

        for (StockOutInfoDto stockOutInfoDto : stockOutInfos.getRecords()) {
            //添加单据状态
            stockOutInfoDto.setWodStatusDict(stockOutInfoDto.getWodStatus() + "");
            stockOutInfoDto.setWodStatus(statusMap.get(stockOutInfoDto.getWodStatus() + ""));
            //查看仓库名称
            Warehouse warehouse = warehouseMapper.selectById(stockOutInfoDto.getOutOfStock());
            if (warehouse != null) {
                //添加仓库名称
                stockOutInfoDto.setOutOfStock(warehouse.getWarehouseName());
            }
            //单位名称
            if (stockOutInfoDto.getMaterialUnit()!=null){
//                String unitName = remoteUnitService.getUnitDataByCode(stockOutInfoDto.getMaterialUnit()).getData().getUnitName();
                //添加单位key
                stockOutInfoDto.setMaterialUnitDict(unitByCodeToMap.get(String.valueOf(stockOutInfoDto.getMaterialUnit())).getUnitName());
            }
            //如果该物料配置了多单位，就进行单位转换
//            if (stockOutInfoDto.getMaterialMoreUnit() != null) {
//                //转换
//                UnitConversionDto unitConversionDto = unitUtil.atWillunitConversion(String.valueOf(stockOutInfoDto.getMaterialUnit()), stockOutInfoDto.getMaterialCode(),
//                    String.valueOf(stockOutInfoDto.getPlannedWeight()), stockOutInfoDto.getMaterialId());
//                if (unitConversionDto != null) {
//                    stockOutInfoDto.setUnitConversion(unitConversionDto.getMaterialMoreUnitNumber());
//                }
//            }
            //单位转换
            String s = unitUtil.unitC(stockOutInfoDto.getMaterialCode(),
                String.valueOf(stockOutInfoDto.getPlannedWeight()),
                stockOutInfoDto.getMaterialId(),
                unitByCodeToMap.get(String.valueOf(stockOutInfoDto.getMaterialUnit())).getUnitName());
            stockOutInfoDto.setUnitConversion(s);

            //添加单位值
            stockOutInfoDto.setMaterialUnit(stockOutInfoDto.getMaterialUnit());


            //添加单据类型
            stockOutInfoDto.setDocumentType(DocumentTypeEnum.getValue(Integer.parseInt(stockOutInfoDto.getDocumentType())));

            //收发类型
            stockOutInfoDto.setTransceiverTypeDict(typeMap.get(stockOutInfoDto.getTransceiverType()));

            //添加生产方式
            stockOutInfoDto.setGenerationMode(GenerationMethodEnum.getValue(Integer.parseInt(stockOutInfoDto.getGenerationMode())));

            //辅助属性
            List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + stockOutInfoDto.getTenantId(), String.valueOf(stockOutInfoDto.getMaterialId()));
            stockOutInfoDto.setAuxiliaryAttribute(statsArray);
        }
        return TableDataInfo.build(stockOutInfos);
    }


    /**
     * 生产确认
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirm(Long id) {
        //查询当前id的状态
        StockOutInfo stockOutInfo = getOne(new QueryWrapper<StockOutInfo>().lambda().select(StockOutInfo::getWodStatus).eq(StockOutInfo::getId, id));
        //获取当前状态
        int wodStatus = stockOutInfo.getWodStatus();
        if (wodStatus != 1) {
            throw new GlobalException("只能对状态为“待确认”的单据进行生产确认");
        }
        //修改单据状态为待出库
        StockOutInfo update = new StockOutInfo();
        update.setId(id);
        update.setWodStatus(2);
        return updateById(update);
    }

    /**
     * 修改单据
     *
     * @param productionPickingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDoc(ProductionPickingVo productionPickingVo) {
        //查询当前id对应的单据
        StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(productionPickingVo.getId());
        //获取当前单据状态
        int wodStatus = stockOutInfo.getWodStatus();
        if (wodStatus != 1) {
            throw new GlobalException("只能对状态为“待确认”的单据进行修改");
        }

        //设置修改的值
        //领用产线
        stockOutInfo.setProductionLine(productionPickingVo.getProductionLine());
        //收发类型
        stockOutInfo.setTransceiverType(productionPickingVo.getTransceiverType());
        //出库日期
        stockOutInfo.setDateDelivery(productionPickingVo.getDateDelivery());
        //备注
        stockOutInfo.setRemark(productionPickingVo.getRemark());

        List<ProductionPickingRelationVo> list = productionPickingVo.getList();
        ProductionPickingRelationVo productionPickingRelationVo = list.get(0);
        stockOutInfo.setMoNumber(productionPickingVo.getMoNumber());
        stockOutInfo.setPlannedWeight(productionPickingRelationVo.getPlannedWeight());
        stockOutInfo.setOutOfStock(productionPickingRelationVo.getOutOfStock());
        stockOutInfo.setMaterialUnit(Long.parseLong(productionPickingRelationVo.getMaterialUnit()));
        stockOutInfo.setDrawerTime(productionPickingVo.getDrawerTime());
        stockOutInfo.setSalesOrderNum(productionPickingVo.getSalesOrderNum());
        return updateById(stockOutInfo);

    }

    /**
     * 查看物料信息
     *
     * @param id
     * @return
     */
    @Override
    public StockOutInfoDto view(Long id) {
        StockOutInfoDto stockOutInfoDto = stockOutInfoMapper.getproductionPickingLById(id);


        //添加单据类型
        stockOutInfoDto.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(stockOutInfoDto.getDocumentType())));
        stockOutInfoDto.setDocumentType(stockOutInfoDto.getDocumentType());

        //定义查看明细列表
        List<ProductionPickingViewDto> list = new ArrayList<>();

        ProductionPickingViewDto productionPickingViewDto = new ProductionPickingViewDto();


        //根据仓库id查出仓库名称
        if (stockOutInfoDto.getOutOfStock() != null) {
            Warehouse warehouse = warehouseMapper.selectById(stockOutInfoDto.getOutOfStock());
            if (warehouse != null) {
                //添加仓库名称
                productionPickingViewDto.setOutOfStockDict(warehouse.getWarehouseName());
                productionPickingViewDto.setOutOfStock(stockOutInfoDto.getOutOfStock() + "");
            }
        }

        if (stockOutInfoDto.getMaterialUnit()!=null){
            String unitName = remoteUnitService.getUnitDataByCode(stockOutInfoDto.getMaterialUnit()).getData().getUnitName();
            //添加单位值
            productionPickingViewDto.setMaterialUnitDict(unitName);
        }

        //添加单位key
        productionPickingViewDto.setMaterialUnit(stockOutInfoDto.getMaterialUnit() + "");

        //添加物料名称,物料编码,物料规格
        productionPickingViewDto.setMaterialCode(stockOutInfoDto.getMaterialCode());
        productionPickingViewDto.setMaterialName(stockOutInfoDto.getItemName());
        productionPickingViewDto.setMaterialSpec(stockOutInfoDto.getItemSpec());

        //添加计划量
        productionPickingViewDto.setPlannedWeight(stockOutInfoDto.getPlannedWeight());

        //制令单
        productionPickingViewDto.setMoNumber(stockOutInfoDto.getMoNumber());

        //辅助属性
        List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + stockOutInfoDto.getTenantId(), String.valueOf(stockOutInfoDto.getMaterialId()));
        productionPickingViewDto.setAuxiliaryAttribute(statsArray);

        //产地
        productionPickingViewDto.setMaterialPlace(stockOutInfoDto.getMaterialPlace());

        list.add(productionPickingViewDto);
        stockOutInfoDto.setList(list);
        return stockOutInfoDto;
    }

    /**
     * 删除单据
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDoc(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() == 0) {
            throw new GlobalException("请至少勾选一条单据");
        }
        //根据ids批量查询出list列表
        List<StockOutInfo> stockOutInfos = stockOutInfoMapper.selectBatchIds(idStr);

        //遍历
        for (StockOutInfo stockOutInfo : stockOutInfos) {
            if (stockOutInfo.getWodStatus() != 1) {
                throw new GlobalException("只能删除待确认下的单据");
            } else if (stockOutInfo.getGenerationMode() != 2) {
                throw new GlobalException("系统自动生成的单据不可删除");
            }
        }
        return removeBatchByIds(idStr);

    }

    /**
     * 关结单据
     *
     * @param productionPickingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeDoc(ProductionPickingVo productionPickingVo) {

        //查询是否有关联单据，如果有则关结单据

        StockOutInfo stockOutInfo = getById(productionPickingVo.getId());
        int status = stockOutInfo.getWodStatus();

        if (status == 6 || status == 7) {
            throw new GlobalException("不可对已关结和已完成状态的单据进行重复关结");
        }


        //根据单号获取生产领料单明细
        List<StockOutInfoDetail> stockOutInfoDetailList = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

        ArrayList<WmsStockInfo> wmsStockInfos = new ArrayList<>();

        for (StockOutInfoDetail stockOutInfoDetail : stockOutInfoDetailList) {
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stockOutInfoDetail.getMaterialNumber()));
            if (wmsStockInfo != null) {
                wmsStockInfos.add(wmsStockInfo);
            }

        }

        if (wmsStockInfos.size() > 0) {
            boolean b = wmsStockInfoMapper.deleteBatchIds(wmsStockInfos) > 0;
        }


        //取出关结人
        String closeMan = stockOutInfo.getCloseMan();
        if (closeMan != null) {
            closeMan = closeMan + "," + LoginHelper.getUsername();
        } else {
            closeMan = LoginHelper.getUsername();
        }

        stockOutInfo.setId(productionPickingVo.getId())
            .setWodStatus(7).setCloseTime(new Date())
            .setCloseMan(closeMan)
            .setCloseCause(productionPickingVo.getCloseCause());
        return updateById(stockOutInfo);
    }

    /**
     * 导出
     *
     * @param productionPickingVo
     * @return
     */
    @Override
    public List<ProductionPickingExport> getInfoExport(ProductionPickingVo productionPickingVo) {


        //获取ids
        String idStr = productionPickingVo.getIdStr();

        if (idStr != null) {

            List<String> idList = Arrays.asList(idStr.split(","));
            productionPickingVo.setIds(idList);
        }

        List<ProductionPickingExport> list = stockOutInfoMapper.getInfoExport(productionPickingVo);

        //根据字典查出收发类型
        List<SysDictData> receivType = DictUtils.getDictCache("stock_out_info_type");
        Map<String, String> typeMap = receivType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (ProductionPickingExport pickingExport : list) {
            pickingExport.setTransceiverTypeDict(typeMap.get(pickingExport.getTransceiverTypeDict()));
        }

        return list;
    }

    /**
     * Pda出库
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto out(PickingRestDbVo pickingRestDbVo) throws Exception {
        //出库类型
        String type = pickingRestDbVo.getType();
        //输入值
        String inputValue = pickingRestDbVo.getInputValue();

        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();

        //判断是否超收或者超发
        //获取菜单id
        Long menuId = remoteMenuService.getIdByMenuName("生产领料");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        StockOutInfo stockOutInfoInfo = getById(pickingRestDbVo.getId());

        PublicMaterial publicMaterial = publicMaterialMapper.selectOne(new QueryWrapper<PublicMaterial>().lambda().eq(PublicMaterial::getMaterialCode, stockOutInfoInfo.getMaterialCode()));

        String unitName = remoteUnitService.getUnitDataByCode(publicMaterial.getMaterialUnit()).getData().getUnitName();

        //如果是扫码出库
        if ("1".equals(type)) {
            //判断扫描的物料条码是否一致
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 2));
            if (wmsStockInfo == null) {
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }

            if ("1".equals(wmsStockInfo.getWsiFreezeInfo())) {
                throw new GlobalException("此物料已冻结请重新输入");
            }

            //扫描的物料编码
            String wsiMaterialCode = wmsStockInfo.getWsiMaterialCode();
            //查询生产领料单中的物料编码
            StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(pickingRestDbVo.getId());

            if (!stockOutInfo.getMaterialCode().equals(wsiMaterialCode)) {
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }

            //判断是否重复扫描(在明细表中查询是否有该条码)
            StockOutInfoDetail stockOutInfoDetail1 = stockOutInfoDetailMapper.selectOne(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getMaterialNumber, inputValue).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));
            if (stockOutInfoDetail1 != null) {
                pickingRestDbDto.setMessage("请勿重复扫描");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }

            StockOutInfoDetail stockOutInfoDetail = new StockOutInfoDetail();

            //物料号码
            stockOutInfoDetail.setMaterialNumber(inputValue);

            //物料状态
            stockOutInfoDetail.setStatus("3");

            //物料编码
            stockOutInfoDetail.setMaterialCode(stockOutInfo.getMaterialCode());

            //关联单号
            stockOutInfoDetail.setWodDocNum(stockOutInfo.getWodDocNum());

            //出库数量
            stockOutInfoDetail.setOutgoingNumber(String.valueOf(wmsStockInfo.getWsiNetWeight()));

            //批次号
            stockOutInfoDetail.setBatchNumber(wmsStockInfo.getWsiMaterialBatch());

            //供应商编码
            stockOutInfoDetail.setSupplierCode(wmsStockInfo.getWsiSupplierCode());

            //仓储信息
            stockOutInfoDetail.setWarehouseInfo(wmsStockInfo.getWsiWarehourseInfo());

            //出库人
            stockOutInfoDetail.setDepositor(LoginHelper.getUsername());
            //单位
            stockOutInfoDetail.setMaterialUnit(String.valueOf(wmsStockInfo.getMaterialUnit()));

            //出库时间
            stockOutInfoDetail.setDeliveryTime(new Date());

            //判断是否有检验
            int docInspectionMark = sysDocument.getDocInspectionMark();
            //如果有检验
            if (docInspectionMark == 1) {
                //修改单据明细为待检验
                stockOutInfoDetail.setStatus("1");
            } else {
                //判断是否有交接
                int docHandoverMark = sysDocument.getDocHandoverMark();
                //有交接
                if (docHandoverMark == 1) {
                    //修改单据明细为待交接
                    stockOutInfoDetail.setStatus("2");
                }
            }
            //添加明细
            stockOutInfoDetailMapper.insert(stockOutInfoDetail);

            //修改生产领料单的单据状态为出库中
            stockOutInfo.setWodStatus(3);
            //修改出库重量和出库数量
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(stockOutInfo.getOutgoingWeight()));
            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));

            BigDecimal add = bigDecimal.add(bigDecimal1);
            stockOutInfo.setOutgoingWeight(add.doubleValue());
            stockOutInfo.setOutgoingNumber(stockOutInfo.getOutgoingNumber() + 1);

            //实际量
            stockOutInfo.setActualNumber(stockOutInfo.getOutgoingWeight());

            updateById(stockOutInfo);

            //修改仓库物料的状态为备料
            wmsStockInfo.setWsiMaterialStatus(5);
            int i = wmsStockInfoMapper.updateById(wmsStockInfo);


            //返回前端参数
            //计划/实际
            pickingRestDbDto.setQuantityIdentification(stockOutInfo.getPlannedWeight() + "/" + stockOutInfo.getActualNumber() + unitName);
            //出库数量
            pickingRestDbDto.setAllotNumOut(stockOutInfo.getOutgoingNumber() + "");

            pickingRestDbDto.setMessage("物料号码:" + inputValue + ",出库量:" + wmsStockInfo.getWsiNetWeight() + "录入成功");
            pickingRestDbDto.setCode("200");

            OutboundLog outboundLog = new OutboundLog();
            BeanUtils.copyProperties(wmsStockInfo,outboundLog,new String[]{"id"});
            outboundLog.setWodDocNum(stockOutInfo.getWodDocNum());
            outboundLogService.save(outboundLog);
            pickingRestDbDto.setPickingPrompt(point(stockOutInfo.getId()).getCombinationName());

            //查询当前生产领料单
            StockOutInfo stockOutInfo1 = stockOutInfoMapper.selectById(pickingRestDbVo.getId());
            //判断是否有超收
            int docHairMark = sysDocument.getDocHairMark();
            //没有超发
            if (docHairMark != 1) {

                //计划出库重量
                Double allotAmount = stockOutInfo1.getPlannedWeight();
                //实际出库重量
                Double allotWeightOut = stockOutInfo1.getActualNumber();
                if (allotWeightOut >= allotAmount) {
                    //判断是否有交接
                    int docHandoverMark = sysDocument.getDocHandoverMark();
                    //有交接
                    if (docHandoverMark == 1) {
                        //修改单据为待交接
                        stockOutInfo1.setWodStatus(5);
                        stockOutInfoMapper.updateById(stockOutInfo1);

                    } else {
                        //修改单据为yiwanc
                        stockOutInfo1.setWodStatus(6);

                        //删除库存
                        List<WmsStockInfo> list = new ArrayList<WmsStockInfo>();
                        //List<LineStock> lineStockList = new ArrayList<>();
                        //新增线边仓数据
                        List<StockOutInfoDetail> stockOutInfoDetail3 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                        //拆包要修改的库存集合
                        List<WmsStockInfo> updateList = new ArrayList<WmsStockInfo>();

                        for (StockOutInfoDetail stock : stockOutInfoDetail3) {

                            if ("1".equals(stock.getIsPackage())){
                                //如果是拆包的

                                //查询库存扣减数量，如果扣完数量为0则删掉库存
                                String materialNumber = stock.getMaterialNumber();
                                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));
                                WmsStockInfo chaiWmsStock = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                                BigDecimal wmsBig = new BigDecimal(String.valueOf(chaiWmsStock.getWsiNetWeight()));
                                BigDecimal outNumBig = new BigDecimal(stock.getOutgoingNumber());
                                BigDecimal subtract = wmsBig.subtract(outNumBig);
                                boolean flag = subtract.compareTo(BigDecimal.ZERO)==0;
                                if (flag){
                                    list.add(chaiWmsStock);
                                }else{
                                    chaiWmsStock.setWsiMaterialStatus(2);
                                    chaiWmsStock.setWsiNetWeight(subtract.doubleValue());
                                    updateList.add(chaiWmsStock);
                                }
                            }else{
                                WmsStockInfo wmsStockInfo1 = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stock.getMaterialNumber()));
                                if(wmsStockInfo1 !=null){
                                    list.add(wmsStockInfo1);
                                }
                            }
                        }
                        if (updateList.size()>0){
                            wmsStockInfoService.updateBatchById(updateList);
                        }

                        if (list.size()>0){
                            wmsStockInfoMapper.deleteBatchIds(list);
                        }

                        stockOutInfoMapper.updateById(stockOutInfo1);

                    }

                }
            }

        } else if ("2".equals(type)) {


            //批次出库
            //查询当前批次对应单条码信息
            List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 2).notIn(WmsStockInfo::getWsiFreezeInfo, 1));

            if (wmsStockInfoList.size() == 0) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("扫描失败，此批次在仓库中的数量为0");
                return pickingRestDbDto;
            }

            Double netWeight = wmsStockInfoMapper.getNetWeight(inputValue);

            List<StockOutInfoDetail> list = new ArrayList<StockOutInfoDetail>();

            //查询生产领料单中的物料编码、
            StockOutInfo stockOutInfo11 = stockOutInfoMapper.selectById(pickingRestDbVo.getId());


            List<OutboundLog> outboundLogList = new ArrayList<>();

            for (WmsStockInfo wmsStockInfo : wmsStockInfoList) {


                //扫描的物料编码
                String wsiMaterialCode = wmsStockInfo.getWsiMaterialCode();

                if (!stockOutInfo11.getMaterialCode().equals(wsiMaterialCode)) {
                    pickingRestDbDto.setCode("500");
                    pickingRestDbDto.setMessage("扫描失败，请核实后扫描");

                    return pickingRestDbDto;
                }
                //新增生产领料明细
                StockOutInfoDetail stockOutInfoDetail = new StockOutInfoDetail();
                //物料号码
                stockOutInfoDetail.setMaterialNumber(wmsStockInfo.getWsiMaterialNumber());
                //物料状态
                stockOutInfoDetail.setStatus("3");
                //物料编码
                stockOutInfoDetail.setMaterialCode(stockOutInfo11.getMaterialCode());
                //关联单号
                stockOutInfoDetail.setWodDocNum(stockOutInfo11.getWodDocNum());
                //出库数量
                stockOutInfoDetail.setOutgoingNumber(String.valueOf(wmsStockInfo.getWsiNetWeight()));
                //批次号
                stockOutInfoDetail.setBatchNumber(wmsStockInfo.getWsiMaterialBatch());
                //供应商编码
                stockOutInfoDetail.setSupplierCode(wmsStockInfo.getWsiSupplierCode());
                //仓储信息
                stockOutInfoDetail.setWarehouseInfo(wmsStockInfo.getWsiWarehourseInfo());
                //出库人
                stockOutInfoDetail.setDepositor(LoginHelper.getUsername());
                //出库时间
                stockOutInfoDetail.setDeliveryTime(new Date());
                //单位
                stockOutInfoDetail.setMaterialUnit(String.valueOf(wmsStockInfo.getMaterialUnit()));

                //判断是否有检验
                int docInspectionMark = sysDocument.getDocInspectionMark();
                //如果有检验
                if (docInspectionMark == 1) {
                    //修改单据明细为待检验
                    stockOutInfoDetail.setStatus("1");
                } else {
                    //判断是否有交接
                    int docHandoverMark = sysDocument.getDocHandoverMark();
                    //有交接
                    if (docHandoverMark == 1) {
                        //修改单据明细为待交接
                        stockOutInfoDetail.setStatus("2");

                    }
                }

                //修改出库重量和出库数量
                BigDecimal bigDecimal = new BigDecimal(stockOutInfo11.getOutgoingWeight());
                BigDecimal bigDecimal1 = new BigDecimal(wmsStockInfo.getWsiNetWeight());

                BigDecimal add = bigDecimal.add(bigDecimal1);
                stockOutInfo11.setOutgoingWeight(add.doubleValue());
                stockOutInfo11.setOutgoingNumber(stockOutInfo11.getOutgoingNumber() + 1);

                //添加明细
                list.add(stockOutInfoDetail);

                //修改仓库物料的状态为备料
                wmsStockInfo.setWsiMaterialStatus(5);


                 OutboundLog outboundLog = new OutboundLog();
                 BeanUtils.copyProperties(wmsStockInfo,outboundLog,new String[]{"id"});
                 outboundLog.setWodDocNum(stockOutInfo11.getWodDocNum());
                 outboundLogList.add(outboundLog);

            }

            //新增明细
            stockInfoDetailService.saveBatch(list);

            wmsStockInfoMapper.updateBatchById(wmsStockInfoList);

            //修改生产领料单的单据状态为出库中
            stockOutInfo11.setWodStatus(3);

            //实际量
            stockOutInfo11.setActualNumber(stockOutInfo11.getOutgoingWeight());

            updateById(stockOutInfo11);


            StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(pickingRestDbVo.getId());
            //返回前端参数
            //计划/实际
            pickingRestDbDto.setQuantityIdentification(stockOutInfo.getPlannedWeight() + "/" + stockOutInfo.getActualNumber() + unitName);
            //出库数量
            pickingRestDbDto.setAllotNumOut(stockOutInfo.getOutgoingNumber() + "");

            pickingRestDbDto.setMessage("批次号:" + inputValue +"出库量:"+netWeight +",数量:" + wmsStockInfoList.size() + "录入成功");
            pickingRestDbDto.setCode("200");

            outboundLogService.saveBatch(outboundLogList);
            pickingRestDbDto.setPickingPrompt(point(stockOutInfo.getId()).getCombinationName());

            //查询当前生产领料单
            StockOutInfo stockOutInfo1 = stockOutInfoMapper.selectById(pickingRestDbVo.getId());
            //判断是否有超发
            int docHairMark = sysDocument.getDocHairMark();
            //没有超发
            if (docHairMark != 1) {

                //计划出库重量
                Double allotAmount = stockOutInfo1.getPlannedWeight();
                //实际出库重量
                Double allotWeightOut = stockOutInfo1.getActualNumber();
                if (allotWeightOut >= allotAmount) {

                    //判断是否有交接
                    int docHandoverMark = sysDocument.getDocHandoverMark();
                    //有交接
                    if (docHandoverMark == 1) {
                        //修改单据为待交接
                        stockOutInfo1.setWodStatus(5);
                        stockOutInfoMapper.updateById(stockOutInfo1);

                    } else {
                        //修改单据为yiwanc
                        stockOutInfo1.setWodStatus(6);

                        //删除库存
                        List<WmsStockInfo> deleteList = new ArrayList<WmsStockInfo>();
                        //List<LineStock> lineStockList = new ArrayList<>();
                        //新增线边仓数据
                        List<StockOutInfoDetail> stockOutInfoDetail3 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                        //拆包要修改的库存集合
                        List<WmsStockInfo> updateList = new ArrayList<WmsStockInfo>();

                        for (StockOutInfoDetail stock : stockOutInfoDetail3) {

                            if ("1".equals(stock.getIsPackage())){
                                //如果是拆包的

                                //查询库存扣减数量，如果扣完数量为0则删掉库存
                                String materialNumber = stock.getMaterialNumber();
                                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));
                                WmsStockInfo chaiWmsStock = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                                BigDecimal wmsBig = new BigDecimal(String.valueOf(chaiWmsStock.getWsiNetWeight()));
                                BigDecimal outNumBig = new BigDecimal(stock.getOutgoingNumber());
                                BigDecimal subtract = wmsBig.subtract(outNumBig);
                                boolean flag = subtract.compareTo(BigDecimal.ZERO)==0;
                                if (flag){
                                    deleteList.add(chaiWmsStock);
                                }else{
                                    chaiWmsStock.setWsiMaterialStatus(2);
                                    chaiWmsStock.setWsiNetWeight(subtract.doubleValue());
                                    updateList.add(chaiWmsStock);
                                }
                            }else{
                                WmsStockInfo wmsStockInfo1 = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stock.getMaterialNumber()));

                                if (wmsStockInfo1!=null){
                                    deleteList.add(wmsStockInfo1);
                                }
                            }
                        }
                        if (updateList.size()>0){
                            wmsStockInfoService.updateBatchById(updateList);
                        }
                        if (list.size()>0){
                            wmsStockInfoMapper.deleteBatchIds(list);
                        }
                        stockOutInfoMapper.updateById(stockOutInfo1);

                    }
                }
            }

        } else if ("3".equals(type)) {
            //条码撤销
            StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(pickingRestDbVo.getId());

            if (stockOutInfo.getWodStatus() != 2 && stockOutInfo.getWodStatus() != 3) {
                throw new GlobalException("只能对待出库和出库中的单据进行条码撤销");
            }


            //在明细表中查询是否有此条码
            StockOutInfoDetail stockOutInfoDetail = stockOutInfoDetailMapper.selectOne(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getMaterialNumber, inputValue).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));
            if (stockOutInfoDetail == null) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("撤销失败");
                return pickingRestDbDto;
            }

            //如果是拆包
            if ("1".equals(stockOutInfoDetail.getIsPackage())){
                //删除条码打印数据
                BarCodePrint barCodePrint = barCodePrintingMapper.selectOne(new QueryWrapper<BarCodePrint>().lambda().eq(BarCodePrint::getMaterialNumber, inputValue).eq(BarCodePrint::getConnectDoc, stockOutInfoDetail.getWodDocNum()));
                barCodePrintingService.removeById(barCodePrint);
                //修改库存状态为在库
                String wmsNumber = inputValue.substring(0, inputValue.lastIndexOf("-"));

                //删除明细
                //修改库存状态为在库
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, wmsNumber));

                wmsStockInfo.setWsiMaterialStatus(2);
                wmsStockInfoMapper.updateById(wmsStockInfo);


                OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWsiMaterialNumber, wmsNumber).eq(OutboundLog::getWodDocNum,stockOutInfo.getWodDocNum()));
                // //删除日志
                outboundLogService.removeById(outboundLog);
                //修改出库重量
                BigDecimal out = new BigDecimal(stockOutInfo.getOutgoingWeight());
                BigDecimal bigDecimal = new BigDecimal(wmsStockInfo.getWsiNetWeight());
                BigDecimal outWeight = out.subtract(bigDecimal);
                //修改出库重量
                stockOutInfo.setOutgoingWeight(outWeight.doubleValue());
                stockOutInfo.setActualNumber(outWeight.doubleValue());

                //删除条码打印
                int delete = barCodePrintingMapper.delete(new QueryWrapper<BarCodePrint>().lambda().eq(BarCodePrint::getConnectDoc, stockOutInfoInfo.getWodDocNum()).eq(BarCodePrint::getMaterialNumber, stockOutInfoDetail.getMaterialNumber()));

                //删除出库明细
                stockOutInfoDetailMapper.delete(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getMaterialNumber, inputValue));

                int i = stockOutInfoMapper.updateById(stockOutInfo);
                if (i <= 0) {
                    pickingRestDbDto.setMessage("撤销失败");
                    pickingRestDbDto.setCode("500");
                }
                //计划/实际
                pickingRestDbDto.setQuantityIdentification(stockOutInfo.getPlannedWeight() + "/" + stockOutInfo.getActualNumber() + unitName);
                //出库数量
                pickingRestDbDto.setAllotNumOut(stockOutInfo.getOutgoingNumber() + "");
                pickingRestDbDto.setMessage("物料号码:" + inputValue + ",出库量:" + stockOutInfoDetail.getOutgoingNumber() + "撤销成功");
                pickingRestDbDto.setCode("200");

            }else {
                //修改库存状态为在库
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));

                wmsStockInfo.setWsiMaterialStatus(2);
                wmsStockInfoMapper.updateById(wmsStockInfo);


                OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWsiMaterialNumber, inputValue));
                // //删除日志
                outboundLogService.removeById(outboundLog);

                BigDecimal out = new BigDecimal(stockOutInfo.getOutgoingWeight());
                BigDecimal bigDecimal = new BigDecimal(stockOutInfoDetail.getOutgoingNumber());
                BigDecimal outWeight = out.subtract(bigDecimal);
                //修改出库重量
                stockOutInfo.setOutgoingWeight(outWeight.doubleValue());

                //扣除数量
                stockOutInfo.setOutgoingNumber(stockOutInfo.getOutgoingNumber() - 1);

                //实际出库重量

                BigDecimal sj = new BigDecimal(String.valueOf(stockOutInfo.getActualNumber()));
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));
                BigDecimal sjWeight = sj.subtract(bigDecimal1);
                stockOutInfo.setActualNumber(sjWeight.doubleValue());

                //删除出库明细
                stockOutInfoDetailMapper.delete(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getMaterialNumber, inputValue));

                int i = stockOutInfoMapper.updateById(stockOutInfo);
                if (i <= 0) {
                    pickingRestDbDto.setMessage("撤销失败");
                    pickingRestDbDto.setCode("500");
                }
                //计划/实际
                pickingRestDbDto.setQuantityIdentification(stockOutInfo.getPlannedWeight() + "/" + stockOutInfo.getActualNumber() + unitName);
                //出库数量
                pickingRestDbDto.setAllotNumOut(stockOutInfo.getOutgoingNumber() + "");
                pickingRestDbDto.setMessage("物料号码:" + inputValue + ",出库量:" + stockOutInfoDetail.getOutgoingNumber() + "撤销成功");
                pickingRestDbDto.setCode("200");
            }
        }

        //拆包
        if ("4".equals(type)){

            //判断扫描的物料条码是否一致
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 2));
            if (wmsStockInfo == null) {
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }

            if ("1".equals(wmsStockInfo.getWsiFreezeInfo())) {
                throw new GlobalException("此物料已冻结请重新输入");
            }

            //扫描的物料编码
            String wsiMaterialCode = wmsStockInfo.getWsiMaterialCode();
            //查询生产领料单中的物料编码
            StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(pickingRestDbVo.getId());

            if (!stockOutInfo.getMaterialCode().equals(wsiMaterialCode)) {
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }

            //判断是否重复扫描(在明细表中查询是否有该条码)
            StockOutInfoDetail stockOutInfoDetail1 = stockOutInfoDetailMapper.selectOne(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getMaterialNumber, inputValue).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));
            if (stockOutInfoDetail1 != null) {
                pickingRestDbDto.setMessage("请勿重复扫描");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }

            //出库数量
            String outNum = pickingRestDbVo.getOutNum();

            if (wmsStockInfo.getWsiNetWeight()<Double.parseDouble(outNum)){
                    pickingRestDbDto.setMessage("出库数量不能大于库存数量");
                    pickingRestDbDto.setCode("500");
                    return pickingRestDbDto;
            }

            //查询条码打印表中是否有流水号，如果没用就是001
            BarCodePrint barCodePrint1 = barCodePrintingMapper.selectOne(new QueryWrapper<BarCodePrint>().lambda().eq(BarCodePrint::getConnectDoc, stockOutInfo.getWodDocNum()));

            //截取物料号码前半部分
            String qz = wmsStockInfo.getWsiMaterialNumber();

            //新号码
            String newNumber = "";

            if (barCodePrint1 == null) {
                newNumber = qz + "-" +"01";
            }else{
                //获取当前的最大流水号
                String maxNumber = barCodePrintingMapper.getMaxNumber(qz);
                //当前最大流水号+1
                String manxNumber = MaxNumberUtils.getManxNumber(maxNumber);
                newNumber = qz + "-" + manxNumber;
            }


            StockOutInfoDetail stockOutInfoDetail = new StockOutInfoDetail();

            //物料号码
            stockOutInfoDetail.setMaterialNumber(newNumber);

            //物料状态
            stockOutInfoDetail.setStatus("3");

            //物料编码
            stockOutInfoDetail.setMaterialCode(stockOutInfo.getMaterialCode());

            //关联单号
            stockOutInfoDetail.setWodDocNum(stockOutInfo.getWodDocNum());

            //出库数量
            stockOutInfoDetail.setOutgoingNumber(outNum);

            //批次号
            stockOutInfoDetail.setBatchNumber(wmsStockInfo.getWsiMaterialBatch());

            //供应商编码
            stockOutInfoDetail.setSupplierCode(wmsStockInfo.getWsiSupplierCode());

            //仓储信息
            stockOutInfoDetail.setWarehouseInfo(wmsStockInfo.getWsiWarehourseInfo());

            //出库人
            stockOutInfoDetail.setDepositor(LoginHelper.getUsername());
            //单位
            stockOutInfoDetail.setMaterialUnit(String.valueOf(wmsStockInfo.getMaterialUnit()));

            //出库时间
            stockOutInfoDetail.setDeliveryTime(new Date());
            //拆包类型
            stockOutInfoDetail.setIsPackage("1");

            //判断是否有检验
            int docInspectionMark = sysDocument.getDocInspectionMark();
            //如果有检验
            if (docInspectionMark == 1) {
                //修改单据明细为待检验
                stockOutInfoDetail.setStatus("1");
            } else {
                //判断是否有交接
                int docHandoverMark = sysDocument.getDocHandoverMark();
                //有交接
                if (docHandoverMark == 1) {
                    //修改单据明细为待交接
                    stockOutInfoDetail.setStatus("2");
                }
            }
            //添加明细
            stockOutInfoDetailMapper.insert(stockOutInfoDetail);

            //修改生产领料单的单据状态为出库中
            stockOutInfo.setWodStatus(3);
            //修改出库重量和出库数量
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(stockOutInfo.getOutgoingWeight()));
            BigDecimal bigDecimal1 = new BigDecimal(outNum);

            BigDecimal add = bigDecimal.add(bigDecimal1);
            stockOutInfo.setOutgoingWeight(add.doubleValue());
            stockOutInfo.setOutgoingNumber(stockOutInfo.getOutgoingNumber() + 1);

            //实际量
            stockOutInfo.setActualNumber(stockOutInfo.getOutgoingWeight());

            updateById(stockOutInfo);


            //生成条码打印
            BarCodePrint barCodePrint = new BarCodePrint();
            barCodePrint.setMaterialNumber(newNumber);
            barCodePrint.setPrintType("3");
            barCodePrint.setConnectDoc(stockOutInfo.getWodDocNum());
            barCodePrint.setMaterialCode(stockOutInfo.getMaterialCode());
            barCodePrint.setSupplierCode(wmsStockInfo.getWsiSupplierCode());
            barCodePrint.setNetWeight(outNum);
            barCodePrint.setCreateTime(new Date());
            barCodePrint.setCreateUser(LoginHelper.getUsername());
            barCodePrint.setDeptId(LoginHelper.getDeptId());
            barCodePrintingService.save(barCodePrint);
            //修改仓库物料的状态为备料
            wmsStockInfo.setWsiMaterialStatus(5);
            int i = wmsStockInfoMapper.updateById(wmsStockInfo);


            //返回前端参数
            //计划/实际
            pickingRestDbDto.setQuantityIdentification(stockOutInfo.getPlannedWeight() + "/" + stockOutInfo.getActualNumber() + unitName);
            //出库数量
            pickingRestDbDto.setAllotNumOut(stockOutInfo.getOutgoingNumber() + "");

            pickingRestDbDto.setMessage("物料号码:" + inputValue + ",出库量:" + outNum + "录入成功");
            pickingRestDbDto.setCode("200");

            OutboundLog outboundLog = new OutboundLog();
            BeanUtils.copyProperties(wmsStockInfo,outboundLog,new String[]{"id"});
            outboundLog.setWodDocNum(stockOutInfoInfo.getWodDocNum());
            outboundLog.setWsiMaterialNumber(newNumber);
            outboundLogService.save(outboundLog);
            pickingRestDbDto.setPickingPrompt(point(stockOutInfo.getId()).getCombinationName());

            //查询当前生产领料单
            StockOutInfo stockOutInfo1 = stockOutInfoMapper.selectById(pickingRestDbVo.getId());
            //判断是否有超收
            int docHairMark = sysDocument.getDocHairMark();
            //没有超发
            if (docHairMark != 1) {

                //计划出库重量
                Double allotAmount = stockOutInfo1.getPlannedWeight();
                //实际出库重量
                Double allotWeightOut = stockOutInfo1.getActualNumber();
                if (allotWeightOut >= allotAmount) {
                    //判断是否有交接
                    int docHandoverMark = sysDocument.getDocHandoverMark();
                    //有交接
                    if (docHandoverMark == 1) {
                        //修改单据为待交接
                        stockOutInfo1.setWodStatus(5);
                        stockOutInfoMapper.updateById(stockOutInfo1);

                    } else {
                        //修改单据为yiwanc
                        stockOutInfo1.setWodStatus(6);

                        //删除库存
                        List<WmsStockInfo> list = new ArrayList<WmsStockInfo>();
                        //List<LineStock> lineStockList = new ArrayList<>();
                        //新增线边仓数据
                        List<StockOutInfoDetail> stockOutInfoDetail3 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                        //拆包要修改的库存集合
                        List<WmsStockInfo> updateList = new ArrayList<WmsStockInfo>();

                        for (StockOutInfoDetail stock : stockOutInfoDetail3) {

                            if ("1".equals(stock.getIsPackage())){
                                //如果是拆包的

                                //查询库存扣减数量，如果扣完数量为0则删掉库存
                                String materialNumber = stock.getMaterialNumber();
                                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));
                                WmsStockInfo chaiWmsStock = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                                BigDecimal wmsBig = new BigDecimal(String.valueOf(chaiWmsStock.getWsiNetWeight()));
                                BigDecimal outNumBig = new BigDecimal(stock.getOutgoingNumber());
                                BigDecimal subtract = wmsBig.subtract(outNumBig);
                                boolean flag = subtract.compareTo(BigDecimal.ZERO)==0;
                                if (flag){
                                    list.add(chaiWmsStock);
                                }else{
                                    chaiWmsStock.setWsiMaterialStatus(2);
                                    chaiWmsStock.setWsiNetWeight(subtract.doubleValue());
                                    updateList.add(chaiWmsStock);
                                }
                            }else{
                                WmsStockInfo wmsStockInfo1 = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stock.getMaterialNumber()));

                                if (wmsStockInfo1 != null) {
                                    list.add(wmsStockInfo1);
                                }
                            }
                        }
                        if (updateList.size()>0){
                            wmsStockInfoService.updateBatchById(updateList);
                        }

                        if (list.size()>0){
                            wmsStockInfoMapper.deleteBatchIds(list);
                        }

                        stockOutInfoMapper.updateById(stockOutInfo1);

                    }

                }
            }
        }


        return pickingRestDbDto;
    }

    /**
     * 拣货完成
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean finishProduction(Long id) throws Exception {
        //判断当前页面是否有配置送检和交接，如果有则生成品检单

        //获取菜单id
        Long menuId = remoteMenuService.getIdByMenuName("生产领料");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        //查出调拨信息单
        StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(id);

        //判断是否有交接
        int docHandoverMark = sysDocument.getDocHandoverMark();
        //有交接
        if (docHandoverMark == 1) {
            //修改单据状态为待交接
            stockOutInfo.setWodStatus(5);
            return stockOutInfoMapper.updateById(stockOutInfo) > 0;
        }

        //判断是否有超收
        //int docHairMark = sysDocument.getDocHairMark();
        //超收
        //if (docHairMark==1){
        //修改单据状态为已完成
        stockOutInfo.setWodStatus(6);

        //删除库存
        List<WmsStockInfo> list = new ArrayList<WmsStockInfo>();
        //List<LineStock> lineStockList = new ArrayList<>();
        //新增线边仓数据
        List<StockOutInfoDetail> stockOutInfoDetail3 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

        //拆包要修改的库存集合
        List<WmsStockInfo> updateList = new ArrayList<WmsStockInfo>();

        for (StockOutInfoDetail stockOutInfoDetail : stockOutInfoDetail3) {

            if ("1".equals(stockOutInfoDetail.getIsPackage())){
                //如果是拆包的

                //查询库存扣减数量，如果扣完数量为0则删掉库存
                String materialNumber = stockOutInfoDetail.getMaterialNumber();
                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));
                WmsStockInfo chaiWmsStock = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                BigDecimal bigDecimal = new BigDecimal(String.valueOf(chaiWmsStock.getWsiNetWeight()));
                BigDecimal bigDecimal1 = new BigDecimal(stockOutInfoDetail.getOutgoingNumber());
                BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
                boolean flag = subtract.compareTo(BigDecimal.ZERO)==0;
                if (flag){
                    list.add(chaiWmsStock);
                }else{
                    chaiWmsStock.setWsiMaterialStatus(2);
                    chaiWmsStock.setWsiNetWeight(subtract.doubleValue());
                    updateList.add(chaiWmsStock);
                }
            }else{
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stockOutInfoDetail.getMaterialNumber()));

                if (wmsStockInfo!=null){
                    list.add(wmsStockInfo);
                }
            }
        }
        if (updateList.size()>0){
            wmsStockInfoService.updateBatchById(updateList);
        }

        if (list.size()>0){
            wmsStockInfoMapper.deleteBatchIds(list);
        }

        return stockOutInfoMapper.updateById(stockOutInfo) > 0;


    }

    /**
     * 拣货撤销
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean repealProduction(Long id) {
        //修改单据状态为待出库
        StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(id);
        stockOutInfo.setWodStatus(2);
        //实际重量，出库重量，出库数量清空
        stockOutInfo.setActualNumber(0.0);
        stockOutInfo.setOutgoingNumber(0);
        stockOutInfo.setOutgoingWeight(0.0);
        //交接数量，交接重量清空
        stockOutInfo.setOverWeight(0.0);
        stockOutInfo.setOverNum(0);
        stockOutInfoMapper.updateById(stockOutInfo);

        //查询明细
        List<StockOutInfoDetail> stockOutInfoDetailList = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

        //日志表集合
        List<OutboundLog> outboundLogList = outboundLogMapper.selectList(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWodDocNum, stockOutInfo.getWodDocNum()));

        //库存集合
        List<WmsStockInfo> wmsStockInfoList = new ArrayList<>();

        //遍历
        for (StockOutInfoDetail stockOutInfoDetail : stockOutInfoDetailList) {
            //将仓库中的物料全修改为在库
            //修改仓库状态为在库
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stockOutInfoDetail.getMaterialNumber()));
            wmsStockInfo.setWsiMaterialStatus(2);
            wmsStockInfoList.add(wmsStockInfo);

            if ("1".equals(stockOutInfoDetail.getIsPackage())){
                String materialNumber = stockOutInfoDetail.getMaterialNumber();
                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));

                WmsStockInfo wmsStockInfo1 = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                wmsStockInfo1.setWsiMaterialStatus(2);
                wmsStockInfoList.add(wmsStockInfo1);
            }


        }
        //删除日志表中的数据
         outboundLogService.removeBatchByIds(outboundLogList);
        //修改库存
        wmsStockInfoService.updateBatchById(wmsStockInfoList);

        //删除条码打印
        int delete = barCodePrintingMapper.delete(new QueryWrapper<BarCodePrint>().lambda().eq(BarCodePrint::getConnectDoc, stockOutInfo.getWodDocNum()));

        //删除所有明细
        int i = stockOutInfoDetailMapper.delete(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));


        return i > 0;
    }

    /**
     * 出库交接
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestHandoverDto overProduction(PickingRestDbVo pickingRestDbVo) {
        //获取步骤
        int step = pickingRestDbVo.getExecutionOrder();
        //获取输入值
        String inputValue = pickingRestDbVo.getInputValue();
        //返回值
        PickingRestHandoverDto pickingRestHandoverDto = new PickingRestHandoverDto();
        //获取菜单id
        Long menuId = remoteMenuService.getIdByMenuName("生产领料");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);

        //拿到交接方式
        int jjType = Integer.parseInt(sysDocument.getDocHandoverMethod());


        if (step == 1) {


            //校验员工编号
            R<SysUser> byUserName = remoteUserService.getByUserName(pickingRestDbVo.getInputValue());
            SysUser userInfo = byUserName.getData();

            if (userInfo == null) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                return pickingRestHandoverDto;
            }

            //返回交接人
            pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
            pickingRestHandoverDto.setDocHandoverMethod(jjType);

            if (jjType == 1) {
                pickingRestHandoverDto.setMessage("请输入物料条码");
            } else if (jjType == 2) {
                pickingRestHandoverDto.setMessage("请输入批次号");
            } else if (jjType == 3) {
                StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(pickingRestDbVo.getId());
                pickingRestDbVo.setInputValue(stockOutInfo.getWodDocNum());
                //查询物料单位
                String unitName = remoteUnitService.getUnitDataByCode(stockOutInfo.getMaterialUnit()).getData().getUnitName();

                //判断是否存在明细表中
                List<StockOutInfoDetail> stockOutInfoDetailList1 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, pickingRestDbVo.getInputValue()));
                if (stockOutInfoDetailList1 == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //查询当前单据号在明细中是否存在，且状态为待交接
                List<StockOutInfoDetail> stockOutInfoDetailList = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, pickingRestDbVo.getInputValue()).eq(StockOutInfoDetail::getStatus, 2));
                if (stockOutInfoDetailList.size() == 0) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败,请核实后再录入");
                    return pickingRestHandoverDto;
                } else {
                    //查出当前为待交接状态的单据明细,算出总净重和总数量
                    Double sumPiHao = stockOutInfoDetailMapper.getDoc(pickingRestDbVo.getInputValue());
                    //总数量
                    long sumNum = stockOutInfoDetailList.size();

                    //出库重量
                    Double allotAmount = stockOutInfo.getOutgoingWeight();

                    //返回计划/实际
                    //判断是否是kg
                    //(实际交接)
                    Double overWeight = stockOutInfo.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(sumPiHao));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    stockOutInfo.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitName);

                    //保存交接数量，交接重量
                    Integer overNum = stockOutInfo.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    int jjSum = (int) sumNum;
                    stockOutInfo.setOverNum(overNum + jjSum);

                    //取出关节人
                    String closeUser = stockOutInfo.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = LoginHelper.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        stockOutInfo.setCloseMan(name);
                    }

                    if (jj == 1) {
                        if (closeUser == null || "".equals(closeUser)) {
                            stockOutInfo.setCloseMan(name);
                        } else {
                            stockOutInfo.setCloseMan("," + name);
                        }
                    }


                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(stockOutInfo.getOutgoingNumber() + "/" + stockOutInfo.getOverNum());

                    for (StockOutInfoDetail stockOutInfoDetail : stockOutInfoDetailList) {
                        //修改物料状态明细为已出库
                        stockOutInfoDetail.setStatus("3");
                        stockOutInfoDetailMapper.updateById(stockOutInfoDetail);
                    }


                    //判断是否所有物料没有待交接的状态
                    List<StockOutInfoDetail> stockOutInfoDetailList2 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getStatus, 2).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                    if (stockOutInfoDetailList2.size() == 0) {
                        //修改单据状态为已完成
                        stockOutInfo.setWodStatus(6);


                        //删除库存
                        List<WmsStockInfo> list = new ArrayList<WmsStockInfo>();
                        //List<LineStock> lineStockList = new ArrayList<>();
                        //新增线边仓数据
                        List<StockOutInfoDetail> stockOutInfoDetail3 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                        //拆包要修改的库存集合
                        List<WmsStockInfo> updateList = new ArrayList<WmsStockInfo>();

                        for (StockOutInfoDetail stockOutInfoDetail : stockOutInfoDetail3) {

                            if ("1".equals(stockOutInfoDetail.getIsPackage())){
                                //如果是拆包的

                                //查询库存扣减数量，如果扣完数量为0则删掉库存
                                String materialNumber = stockOutInfoDetail.getMaterialNumber();
                                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));
                                WmsStockInfo chaiWmsStock = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                                BigDecimal chaiBig = new BigDecimal(String.valueOf(chaiWmsStock.getWsiNetWeight()));
                                BigDecimal outNumBig = new BigDecimal(stockOutInfoDetail.getOutgoingNumber());
                                BigDecimal subtract = chaiBig.subtract(outNumBig);
                                boolean flag = subtract.compareTo(BigDecimal.ZERO)==0;
                                if (flag){
                                    list.add(chaiWmsStock);
                                }else{
                                    chaiWmsStock.setWsiMaterialStatus(2);
                                    chaiWmsStock.setWsiNetWeight(subtract.doubleValue());
                                    updateList.add(chaiWmsStock);
                                }
                            }else{
                                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stockOutInfoDetail.getMaterialNumber()));
                                if (wmsStockInfo!=null){
                                    list.add(wmsStockInfo);
                                }
                            }
                        }
                        if (updateList.size()>0){
                            wmsStockInfoService.updateBatchById(updateList);
                        }

                        if (list.size()>0){
                            wmsStockInfoMapper.deleteBatchIds(list);
                        }


                    }
                    boolean b = updateById(stockOutInfo);
                    if (!b) {
                        pickingRestHandoverDto.setResultCode("500");
                        pickingRestHandoverDto.setMessage("交接失败");
                        return pickingRestHandoverDto;
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("单据号:" + pickingRestDbVo.getInputValue() +"净含量"+stockOutInfo.getOutgoingWeight()+ ",数量:" + sumNum + ",交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                }
            }
            pickingRestHandoverDto.setResultCode("200");
            return pickingRestHandoverDto;

        } else {
            //如果是单个物料交接
            if (jjType == 1) {
                //查询当前的出库单信息
                StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(pickingRestDbVo.getId());

                String unitName = remoteUnitService.getUnitDataByCode(stockOutInfo.getMaterialUnit()).getData().getUnitName();

                //查询出库明细
                StockOutInfoDetail stockOutInfoDetail = stockOutInfoDetailMapper.selectOne(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getMaterialNumber, inputValue).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));
                if (stockOutInfoDetail == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //判断当前物料是否属于待交接
                if (!"2".equals(stockOutInfoDetail.getStatus())) {
                    pickingRestHandoverDto.setMessage("不可重复交接");
                    pickingRestHandoverDto.setResultCode("500");
                    return pickingRestHandoverDto;
                } else {
                    //出库重量
                    Double allotAmount = stockOutInfo.getOutgoingWeight();

                    //(实际交接)
                    Double overWeight = stockOutInfo.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(stockOutInfoDetail.getOutgoingNumber()));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    stockOutInfo.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitName);

                    Integer overNum = stockOutInfo.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    //保存交接数量，交接重量
                    stockOutInfo.setOverNum(overNum + 1);

                    //取出关节人
                    String closeUser = stockOutInfo.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = LoginHelper.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        stockOutInfo.setCloseMan(name);
                    }


                    if (jj == 1) {
                        stockOutInfo.setCloseMan("," + name);
                    }
                    stockOutInfo.setCloseTime(new Date());

                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(stockOutInfo.getOutgoingNumber() + "/" + stockOutInfo.getOverNum());

                    //修改物料状态明细为已出库
                    stockOutInfoDetail.setStatus("3");
                    stockOutInfoDetailMapper.updateById(stockOutInfoDetail);


                    //判断是否所有物料没有待交接的状态
                    List<StockOutInfoDetail> stockOutInfoDetailList = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getStatus, 2).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));
                    if (stockOutInfoDetailList.size() == 0) {
                        //修改单据状态为已完成
                        stockOutInfo.setWodStatus(6);


                        //删除库存
                        List<WmsStockInfo> list = new ArrayList<WmsStockInfo>();
                        //List<LineStock> lineStockList = new ArrayList<>();
                        //新增线边仓数据
                        List<StockOutInfoDetail> stockOutInfoDetail3 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                        //拆包要修改的库存集合
                        List<WmsStockInfo> updateList = new ArrayList<WmsStockInfo>();

                        for (StockOutInfoDetail detail : stockOutInfoDetail3) {

                            if ("1".equals(detail.getIsPackage())){
                                //如果是拆包的

                                //查询库存扣减数量，如果扣完数量为0则删掉库存
                                String materialNumber = detail.getMaterialNumber();
                                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));
                                WmsStockInfo chaiWmsStock = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                                BigDecimal chaiBig = new BigDecimal(String.valueOf(chaiWmsStock.getWsiNetWeight()));
                                BigDecimal outNumBig = new BigDecimal(detail.getOutgoingNumber());
                                BigDecimal subtract = chaiBig.subtract(outNumBig);
                                boolean flag = subtract.compareTo(BigDecimal.ZERO)==0;
                                if (flag){
                                    list.add(chaiWmsStock);
                                }else{
                                    chaiWmsStock.setWsiMaterialStatus(2);
                                    chaiWmsStock.setWsiNetWeight(subtract.doubleValue());
                                    updateList.add(chaiWmsStock);
                                }
                            }else{
                                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, detail.getMaterialNumber()));
                                if (wmsStockInfo!=null){
                                    list.add(wmsStockInfo);
                                }

                            }
                        }
                        if (updateList.size()>0){
                            wmsStockInfoService.updateBatchById(updateList);
                        }

                        if (list.size()>0){
                            wmsStockInfoMapper.deleteBatchIds(list);
                        }

                    }


                    boolean b = updateById(stockOutInfo);
                    if (!b) {
                        pickingRestHandoverDto.setMessage("交接失败");
                        pickingRestHandoverDto.setResultCode("500");
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("物料号码:" + pickingRestDbVo.getInputValue()+"净含量"+stockOutInfo.getOutgoingWeight() + ",数量:1,交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                }
            } else if (jjType == 2) {
                StockOutInfo stockOutInfo = stockOutInfoMapper.selectById(pickingRestDbVo.getId());

                //查询物料单位
                String unitName = remoteUnitService.getUnitDataByCode(stockOutInfo.getMaterialUnit()).getData().getUnitName();

                //判断是否存在明细表中
                List<StockOutInfoDetail> stockOutInfoDetailList1 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getBatchNumber, pickingRestDbVo.getInputValue()).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));
                if (stockOutInfoDetailList1 == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //查询当前批号在明细中是否存在，且状态为待交接
                List<StockOutInfoDetail> stockOutInfoDetailList = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getBatchNumber, pickingRestDbVo.getInputValue()).eq(StockOutInfoDetail::getStatus, 2).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));
                if (stockOutInfoDetailList.size() == 0) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("不可重复交接");
                    return pickingRestHandoverDto;
                } else {
                    //查出当前为待交接状态的批次，算出总净重和总数量
                    Double sumPiHao = stockOutInfoDetailMapper.getPiHao(pickingRestDbVo.getInputValue());
                    //总数量
                    long sumNum = stockOutInfoDetailList.size();

                    //出库重量
                    Double allotAmount = stockOutInfo.getOutgoingWeight();

                    //返回计划/实际
                    Double overWeight = stockOutInfo.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }
                    //(实际交接)
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(sumPiHao));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    stockOutInfo.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitName + "");


                    //保存交接数量，交接重量
                    Integer overNum = stockOutInfo.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    int jjSum = (int) sumNum;
                    stockOutInfo.setOverNum(overNum + jjSum);

                    //取出关节人
                    String closeUser = stockOutInfo.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = LoginHelper.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        stockOutInfo.setCloseMan(name);
                    }

                    if (jj == 1) {
                        if (closeUser == null || "".equals(closeUser)) {
                            stockOutInfo.setCloseMan(name);
                        } else {
                            stockOutInfo.setCloseMan("," + name);
                        }
                    }
                    stockOutInfo.setCloseTime(new Date());

                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(stockOutInfo.getOutgoingNumber() + "/" + stockOutInfo.getOverNum());

                    for (StockOutInfoDetail stockOutInfoDetail : stockOutInfoDetailList) {
                        //修改物料状态明细为已出库
                        stockOutInfoDetail.setStatus("3");
                    }
                    stockInfoDetailService.updateBatchById(stockOutInfoDetailList);

                    //判断是否所有物料没有待交接的状态
                    List<StockOutInfoDetail> stockOutInfoDetailList2 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getStatus, 2).eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                    if (stockOutInfoDetailList2.size() == 0) {
                        //修改单据状态为已完成
                        stockOutInfo.setWodStatus(6);
                        //删除库存
                        List<WmsStockInfo> list = new ArrayList<WmsStockInfo>();
                        //List<LineStock> lineStockList = new ArrayList<>();
                        //新增线边仓数据
                        List<StockOutInfoDetail> stockOutInfoDetail3 = stockOutInfoDetailMapper.selectList(new QueryWrapper<StockOutInfoDetail>().lambda().eq(StockOutInfoDetail::getWodDocNum, stockOutInfo.getWodDocNum()));

                        //拆包要修改的库存集合
                        List<WmsStockInfo> updateList = new ArrayList<WmsStockInfo>();

                        for (StockOutInfoDetail stockOutInfoDetail : stockOutInfoDetail3) {

                            if ("1".equals(stockOutInfoDetail.getIsPackage())){
                                //如果是拆包的

                                //查询库存扣减数量，如果扣完数量为0则删掉库存
                                String materialNumber = stockOutInfoDetail.getMaterialNumber();
                                String number = materialNumber.substring(0, materialNumber.lastIndexOf("-"));
                                WmsStockInfo chaiWmsStock = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, number));
                                BigDecimal chaiBig = new BigDecimal(String.valueOf(chaiWmsStock.getWsiNetWeight()));
                                BigDecimal outNumBig = new BigDecimal(stockOutInfoDetail.getOutgoingNumber());
                                BigDecimal subtract = chaiBig.subtract(outNumBig);
                                boolean flag = subtract.compareTo(BigDecimal.ZERO)==0;
                                if (flag){
                                    list.add(chaiWmsStock);
                                }else{
                                    chaiWmsStock.setWsiMaterialStatus(2);
                                    chaiWmsStock.setWsiNetWeight(subtract.doubleValue());
                                    updateList.add(chaiWmsStock);
                                }
                            }else{
                                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, stockOutInfoDetail.getMaterialNumber()));
                                if (wmsStockInfo!=null){
                                    list.add(wmsStockInfo);
                                }

                            }
                        }
                        if (updateList.size()>0){
                            wmsStockInfoService.updateBatchById(updateList);
                        }

                        if (list.size()>0){
                            wmsStockInfoMapper.deleteBatchIds(list);
                        }

                    }
                    boolean b = updateById(stockOutInfo);
                    if (!b) {
                        pickingRestHandoverDto.setResultCode("500");
                        pickingRestHandoverDto.setMessage("交接失败");
                        return pickingRestHandoverDto;
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + ",数量:" + sumNum + ",交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                }
            } else if (jjType == 3) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("请勿重复交接");
            }
        }
        return pickingRestHandoverDto;
    }


    /**
     * 拣货提示
     *
     * @param id
     * @return
     */
    @Override
    public SchemeDto point(Long id) {
        StockOutInfo byId = getById(id);
        SchemeVo schemeVo = new SchemeVo();
        if(byId != null){
            schemeVo.setMaterialCode(byId.getMaterialCode());
        }
        schemeVo.setAssociatedDetails("1");
        return pickingSchemeService.getSchemeData(schemeVo);
    }

    /**
     * 全局拣货提示
     *
     * @param schemePdaVo
     * @return
     */
    @Override
    public SchemePdaDto getSchemePdaInfo(SchemePdaVo schemePdaVo) {

        //拣货提示
        SchemePdaDto schemePdaDto = new SchemePdaDto();

        //类型
        String type = schemePdaVo.getType();

        //id
        Long id = schemePdaVo.getId();


        //生产领料
        if ("1".equals(type)) {
            SchemeDto point = point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        } else if ("2".equals(type)) {
            //委外发货单
            SchemeDto point = pickingOutsourceService.point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        } else if ("3".equals(type)) {
            //销售发货单
            SchemeDto point = pickingSaleService.point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        } else if ("4".equals(type)) {
            //其他出库单
            SchemeDto point = pickingRestService.point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        } else if ("5".equals(type)) {
            //调拨单
            SchemeDto point = allotManagementService.point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        } else if ("6".equals(type)) {
            //返工出库
            SchemeDto point = pickingCompleteService.point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        } else if ("7".equals(type)) {
            //采购退货
            SchemeDto point = pickingPurchaseService.point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        } else {
            //委外退货
            SchemeDto point = pickingReturnsService.point(id);
            schemePdaDto.setPickingPrompt(point.getCombinationName());
            return schemePdaDto;
        }
    }


}
